package com.hh.BacktrackQuestions;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author hanghao
 * @Date 2023/7/7 14:27
 * @Version 1.0
 */

public class No17 {
    List<String> result = new ArrayList<>();
    public List<String> letterCombinations(String digits) {
        if (digits == null || digits.length() == 0) return result;
        String[] numString = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        backTracking(digits, numString, 0);
        return result;
    }

    //每次迭代获取一个字符串，所以会设计大量的字符串拼接，所以这里选择更为高效的 StringBuild
    StringBuilder temp = new StringBuilder();

    //比如digits如果为"23",num 为0，则str表示2对应的 abc
    public void backTracking(String digits, String[] numString, int num) {
        if (num == digits.length()) {
            result.add(temp.toString());
            return;
        }
        //str 表示当前num对应的字符串
        //digits.charAt(num) - '0' 为了将字符串 转为 int
        String str = numString[digits.charAt(num) - '0'];
        for (int i = 0; i < str.length(); i++) {
            temp.append(str.charAt(i));
            //回溯
            backTracking(digits,numString,num + 1);
            //剔除末尾的继续尝试
            temp.deleteCharAt(temp.length() - 1);
        }
    }
}
